package com.erp.gather.controller;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gather.api.domain.ErpCollectProductSkuPrice;
import com.erp.gather.domain.bo.ErpCollectProductSkuPriceBo;
import com.erp.gather.domain.vo.ErpCollectProductSkuPriceVo;
import com.erp.gather.mapper.ErpCollectProductSkuMapper;
import com.erp.gather.mapper.ErpCollectProductSkuPriceMapper;
import com.erp.gather.service.IErpCollectProductSkuPriceService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * sku价格
 *
 * @author erp
 * @date 2023-05-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gather/collectProductSkuPrice")
public class ErpCollectProductSkuPriceController extends BaseController {

	private final IErpCollectProductSkuPriceService iErpCollectProductSkuPriceService;
	private final ErpCollectProductSkuPriceMapper erpCollectProductSkuPriceMapper;
	private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;

	/**
	 * 导出不同国家运费相同的sku
	 */
	@GetMapping("/differentCountry")
	public void differentCountry(HttpServletResponse response) {
		//TODO 更换excel方法
//		List<ErpCollectProductSkuPriceVo> vo = iErpCollectProductSkuPriceService.differentCountry();
//		ExcelUtil.exportExcel(vo, "sku价格问题", ErpCollectProductSkuPriceVo.class, response);
	}

	/**
	 * 查询sku价格列表
	 */
	@GetMapping("/list")
	public TableDataInfo<ErpCollectProductSkuPriceVo> list(ErpCollectProductSkuPriceBo bo, PageQuery pageQuery) {
		return iErpCollectProductSkuPriceService.queryPageList(bo, pageQuery);
	}


	/**
	 * 获取sku价格详细信息
	 *
	 * @param id 主键
	 */
	@GetMapping("/{id}")
	public R<ErpCollectProductSkuPriceVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
		return R.ok(iErpCollectProductSkuPriceService.queryById(id));
	}

	/**
	 * 新增sku价格
	 */
	@RepeatSubmit()
	@PostMapping()
	public R<Void> add(@Validated(AddGroup.class) @RequestBody ErpCollectProductSkuPriceBo bo) {
		return toAjax(iErpCollectProductSkuPriceService.insertByBo(bo));
	}

	/**
	 * 修改sku价格
	 */
	@RepeatSubmit()
	@PutMapping()
	public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpCollectProductSkuPriceBo bo) {
		return toAjax(iErpCollectProductSkuPriceService.updateByBo(bo));
	}

	/**
	 * 删除sku价格
	 *
	 * @param ids 主键串
	 */
	@DeleteMapping("/{ids}")
	public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		return toAjax(iErpCollectProductSkuPriceService.deleteWithValidByIds(Arrays.asList(ids), true));
	}

	/**
	 * 刷新定价
	 */
	@GetMapping("/refresh")
	public R<Object> refresh(Long productId) {

		List<Long> resList = new ArrayList<Long>();

		Map<Long, Integer> map = new HashMap<>();
		map.put(1650414275172282368l, 0);
		map.put(1651129417663295488l, 0);
		map.put(1651394954939473922l, 0);
		map.put(1650796884676927490l, 0);
		map.put(1651137439693750274l, 0);
		map.put(1651138936359829506l, 0);

		LambdaQueryWrapper<ErpCollectProductSkuPrice> lqw = Wrappers.lambdaQuery();
		lqw.eq(ErpCollectProductSkuPrice::getOriginalSkuPrice, "0");
		lqw.eq(productId != null, ErpCollectProductSkuPrice::getCollectProductId, productId);
		lqw.groupBy(ErpCollectProductSkuPrice::getCollectProductId);

		List<ErpCollectProductSkuPrice> selectList = erpCollectProductSkuPriceMapper.selectList(lqw);

		// 切割数组进行多线程操作
//		List<List<ErpCollectProductSkuPrice>> averageAssign = CommonUtils.averageAssign(selectList, 300);
//		for (List<ErpCollectProductSkuPrice> list : averageAssign) {
//			Thread thread = new Thread(new Runnable() {
//
//				@Override
//				public void run() {
		for (ErpCollectProductSkuPrice skuPrice : selectList) {
			Long collectProductId = skuPrice.getCollectProductId();
			String originalSkuPrice = skuPrice.getOriginalSkuPrice();
			String freightMap = skuPrice.getFreightMap();
			String globalQuoteMap = skuPrice.getGlobalQuoteMap();
			try {
				if (map.containsKey(collectProductId) && map.get(collectProductId).equals(0)) {
					iErpCollectProductSkuPriceService.saveSkuPrice(collectProductId);
					map.put(collectProductId, 1);
				} else {
					if (StringUtils.isEmpty(freightMap) || StringUtils.isEmpty(globalQuoteMap)) {
						iErpCollectProductSkuPriceService.saveSkuPrice(collectProductId);
					} else {
						if (originalSkuPrice.equals("0")) {
							Dict freightMapDict = JsonUtils.parseMap(freightMap);
							Dict globalQuoteMapDict = JsonUtils.parseMap(globalQuoteMap);

							// 计算日常价格
							BigDecimal USFreightPrice = new BigDecimal(freightMapDict.get("US").toString());
							BigDecimal USGlobalPrice = new BigDecimal(globalQuoteMapDict.get("US").toString());

							BigDecimal price = USGlobalPrice.subtract(USFreightPrice).setScale(2,
									BigDecimal.ROUND_HALF_UP);

							skuPrice.setOriginalSkuPrice(price.toString());
							erpCollectProductSkuPriceMapper.updateById(skuPrice);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				resList.add(collectProductId);
			}
		}
//				}
//			});
//			thread.start();
//		}

		return R.ok();
	}

	/**
	 * 刷新定价
	 */
//	@GetMapping("/refresh")
//	public R<Object> refresh() {
//		List<Long> resList = new ArrayList<Long>();
//		LambdaQueryWrapper<ErpCollectProductSkuPrice> lqw = Wrappers.lambdaQuery();
//		lqw.isNull(ErpCollectProductSkuPrice::getCollectProductId);
//		List<ErpCollectProductSkuPrice> selectList = erpCollectProductSkuPriceMapper.selectList(lqw);
//		List<ErpCollectProductSkuPrice> list = new ArrayList<>();
//		for (ErpCollectProductSkuPrice sku : selectList) {
//			try {
//				ErpCollectProductSku selectOne = erpCollectProductSkuMapper
//						.selectOne(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getSkuCode,
//								sku.getSkuCode()));
//				if (selectOne == null)
//					continue;
//				sku.setCollectProductId(selectOne.getCollectProductId());
//				list.add(sku);
//				if (list.size() % 1000 == 0) {
//					erpCollectProductSkuPriceMapper.updateBatchById(list, 1000);
//					list.clear();
//				}
//			} catch (Exception e) {
//				resList.add(getDeptId());
//			}
//		}
//		if (list.size() > 0) {
//			erpCollectProductSkuPriceMapper.updateBatchById(list, 1000);
//		}
//		return R.ok(resList);
//	}

	/**
	 *
	 * @return
	 */
	@GetMapping("/getErrorPro")
	public R<Object> getErrorPro() {

		Map<Long, Long> map = new HashMap<Long, Long>();

		Long count = erpCollectProductSkuPriceMapper.selectCount(null);

		Long pageIndex = 0l;
		Long pageSize = 500l;
		if (count % 500 == 0) {
			pageIndex = count / 500;
		} else {
			pageIndex = (count / 500) + 1;
		}

		LambdaQueryWrapper<ErpCollectProductSkuPrice> lqw = Wrappers.lambdaQuery();
		lqw.orderByAsc(ErpCollectProductSkuPrice::getId);
		for (int i = 1; i <= pageIndex; i++) {
			Long start = (i - 1) * pageSize;
			lqw.last("limit " + start + ", " + pageSize);
			List<ErpCollectProductSkuPrice> list = erpCollectProductSkuPriceMapper.selectList(lqw);

			for (ErpCollectProductSkuPrice erpCollectProductSkuPrice : list) {

				Long collectProductId = erpCollectProductSkuPrice.getCollectProductId();

				String freightMap = erpCollectProductSkuPrice.getFreightMap();
				Dict parseMap = JsonUtils.parseMap(freightMap);
				for (String key : parseMap.keySet()) {
					Double amount = parseMap.getDouble(key);
					if (amount.equals(0d)) {
						map.put(collectProductId, collectProductId);
					}
				}
			}
		}

		return R.ok(JsonUtils.toJsonString(map.values()));
	}

	/**
	 * 根据SKU code 获取采集商品SKU价格信息
	 * @param skuCode
	 * @return
	 */
	@GetMapping("getBySkuCode/{skuCode}")
	public R<Object> getBySkuCode(@PathVariable("skuCode") String skuCode) {
		ErpCollectProductSkuPrice skuPrice = iErpCollectProductSkuPriceService.getBySkuCode(skuCode);
		if(skuPrice != null){
			return R.ok(skuPrice);
		}
		return R.fail("未查询到商品sku价格信息");
	}
}
